package com.neuedu.jdbc.util;



import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author 金山
 * 项目：jdbc
 * site: https://blog.fulfill.com.cn
 * 描述  数据库的工具
 * @data 2024/11/811:14
 */
public class DBUtils {
    public static final String url = "jdbc:mysql://127.0.0.1:3306/test";
    public static final String driverClass = "com.mysql.cj.jdbc.Driver";
    public static final  String username = "root";
    public static final  String password = "root";

    static{
        try {
            //1加载驱动
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 工具的方法
     * @return
     */
    public static Connection getConnection() throws SQLException {


        //2建立连接

        Connection conn = DriverManager.getConnection(url, username, password);

        return conn;
    }


    /**
     * 关闭资源
     * @param conn
     * @param stmt
     * @param rs
     */

    public  static void close(Connection conn, Statement stmt, ResultSet rs){
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }


}





